﻿using System.Reflection;

namespace Foundation.Core
{
    public class EnumSelectCreateExecutor : ITypeSelectCreateExecutor, IEnumSelectFilterMetadata
    {
        public virtual bool CanHandle(Type type) => type.IsEnum && !type.IsGenericTypeDefinition;

        public virtual object CreateModel(Type type) => null;

        public virtual IList<MemberInfo> GetMemberInfos(Type type)
        {
            if (!CanHandle(type)) return null;

            var members = EnumHelper.GetMembers(type);

            return members.Cast<EnumHelper.EnumMemberMetadataInfo>().Select(a => a.Fieldinfo).ToArray();
        }

        public virtual void Execute(TypeSelectCreateExecuteContext context)
        {
            var name = context.MemberInfo.Name;
            var maps = EnumHelper.GetNameValueMap(context.MemberInfo.DeclaringType);

            if (maps == null || !maps.TryGetValue(name, out var info))
            {
                context.Ignore = true;

                return;
            }

            context.Name = info.Name;
            context.Label = info.Description;
            context.Value = info.NumberValue;
        }
    }
}
